package config

import (
	"github.com/go-ini/ini"
	"log"
	"proxy_resource_test/utils"
	"runtime"
	"time"
)

var ThisAppDir string // 获取当前程序运行目录

var AppConfig app
var DatabaseConfig database
var RedisConf redisConfig
var ClickHouseConfig clickHouseBase

func Init() {
	ThisAppDir = utils.GetAppDir()
	if runtime.GOOS != "windows" {
		ThisAppDir = utils.GetCurrentPath()
	}
	var conf, err = ini.Load(ThisAppDir + "/conf.ini")
	if err != nil {
		log.Fatalf("conf error: %v", err)
	}

	err = conf.Section("App").MapTo(&AppConfig)
	if err != nil {
		log.Fatalf("conf error: %v", err)
	}
	AppConfig.ReadTimeout *= time.Second
	AppConfig.WriteTimeout *= time.Second

	loadSection(conf, "Database", &DatabaseConfig)
	loadSection(conf, "RedisConf", &RedisConf)
	loadSection(conf, "ClickHouseBase", &ClickHouseConfig)
}

// 加载文件内容
func loadSection(cfg *ini.File, section string, target interface{}) {
	err := cfg.Section(section).MapTo(target)
	if err != nil {
		log.Fatalf("Failed to map section [%s]: %v", section, err)
	}
}
